package com.letv.core.sysletvplayer.base;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.letv.android.sdk.R;
import com.letv.core.sysletvplayer.Interface.PlayerControl;
import com.letv.core.sysletvplayer.Interface.PlayerPannelHandler;
import com.letv.core.sysletvplayer.Interface.SystemInfoListener;
import com.letv.core.sysletvplayer.base.impl.LocalPlayerActivity;
import com.letv.core.sysletvplayer.utils.Tools;
import com.letv.core.sysletvplayer.view.LetvGestureLayout.LetvPlayGestureCallBack;

public abstract class BasePlayerController implements PlayerControl, LetvPlayGestureCallBack, SystemInfoListener{
	
	
	/**
	 * 手势 亮度的布局
	 * */
	private View brightnessLayout;
	/**
	 * 手势 声音的布局
	 * */
	private View volumeLayout;
	/**
	 * 手势 亮度的文字提示
	 * */
	private TextView brightnessTextView;
	/**
	 * 手势 声音的文字提示
	 * */
	private TextView volumeTextView;
	/**
	 * 手势 声音icon
	 */
	private ImageView volumeIcon;
	/**
	 * 手势 锁的image
	 * */
	private ImageView lockBar;

	/**
	 * 手势 进度的布局
	 * */
	private View progressLayout;
	
	/**
	 * 手势 当前进度显示
	 * */
	private TextView progressTextView;

	/**
	 * 手势 总长度显示
	 * */
	private TextView totalTextView;
//
//	/**
//	 * 是否上锁
//	 * */
//	protected boolean isLock;
	
	private ProgressBar gestureProgress;

	private ImageView progressIcon;

	private TextView unslidableTextView;

	/**
	 * 手势操作开始的声音点
	 * */
	private int oldV;

	/**
	 * 手势操作开始的亮度点
	 * */
	private int oldB;
	
	/**
	 * 手势操作开始的进度点
	 */
	private int oldP;

	private AudioManager audioManager;

	protected LocalPlayerActivity activity;
	
	protected PlayerPannelHandler mBasePlayerPannel;
	
	public BasePlayerController(LocalPlayerActivity activity) {
		this.activity = activity;
		
		audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
		if (audioManager != null) {
			if (audioManager.getMode() == AudioManager.MODE_INVALID) {
				audioManager.setMode(AudioManager.MODE_NORMAL);
			}
		}
		create();
	}
	
	public void setPannelHandler(PlayerPannelHandler pannel) {
		this.mBasePlayerPannel = pannel;
	}
	
//	private Handler xHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			if (lockBar != null) {
//				lockBar.setVisibility(View.GONE);
//			}
//		};
//	};


	public void create() {
		findGestrueView();
		readArguments();
		initLayout();
		int currentValue = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//		int maxValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//		changeVolume(currentValue, maxValue);
		oldV = currentValue;


//      isLock = PreferencesManager.getInstance().isLockDirection();
//		lockBar.setImageResource(isLock ? R.drawable.lock : R.drawable.unlock);
//		activity.getmOrientationSensorListener().setLock(isLock);
//		activity.getmOrientationSensorListener().setOnDirectionChangeListener(new OnDirectionChangeListener() {
//
//			@Override
//			public void onChange(int orientation, int orientationProperty) {
//				if (lockBar.getVisibility() != View.VISIBLE) {
//					lockBar.setVisibility(View.VISIBLE);
//					startHandlerTime();
//				}
//			}
//		});
//
        float britnes= getBrightnessFromSharedPreferences();
        if(britnes!= 0) {
            setBrightness(britnes);
        }
	}

//	/**
//	 * 倒计时隐藏lock
//	 * */
//	private void startHandlerTime() {
//        if(xHandler != null ) {
//		    xHandler.removeMessages(1);
//		    xHandler.sendEmptyMessageDelayed(1, 3000);
//        }
//	}
//
//    public void showLock() {
//        if (lockBar != null) {
//            lockBar.setVisibility(View.VISIBLE);
//            startHandlerTime();
//        }
//    }
	
	private void findGestrueView() {
		brightnessLayout = activity.getPlayGestrue().findViewById(R.id.brightness_layout);
		volumeLayout = activity.getPlayGestrue().findViewById(R.id.volume_layout);
		brightnessTextView = (TextView) activity.getPlayGestrue().findViewById(R.id.brightness_textview);
		volumeTextView = (TextView) activity.getPlayGestrue().findViewById(R.id.volume_textview);
		volumeIcon = (ImageView) activity.getPlayGestrue().findViewById(R.id.volume_icon);
		lockBar = (ImageView) activity.getPlayGestrue().findViewById(R.id.lock);
		progressLayout = activity.getPlayGestrue().findViewById(R.id.progress_layout);
		progressTextView = (TextView) activity.getPlayGestrue().findViewById(R.id.progress);
		totalTextView = (TextView) activity.getPlayGestrue().findViewById(R.id.total);
		
		gestureProgress = (ProgressBar) activity.getPlayGestrue().findViewById(R.id.gesture_progress);
		progressIcon = (ImageView) activity.getPlayGestrue().findViewById(R.id.gesture_progress_icon);
		unslidableTextView = (TextView) activity.getPlayGestrue().findViewById(R.id.unslidable_text);
		
		brightnessLayout.setVisibility(View.GONE);
		volumeLayout.setVisibility(View.GONE);
		progressLayout.setVisibility(View.GONE);
		
		initVolume(getCurSoundVolume(), getMaxSoundVolume());

		oldB = getMaxBrightness() * 30 / 100; //首次进入30%亮度显示
        float britness= getBrightnessFromSharedPreferences();
        if(britness!= 0) {
            oldB= (int)(britness* 255);
        }
		initBrightness(oldB, getMaxBrightness());
//		 oldB = getCurBrightness();
		activity.getPlayGestrue().initializeData((float) getCurSoundVolume() / getMaxSoundVolume(),
				(float) oldB / getMaxBrightness());
		activity.getPlayGestrue().setLetvPlayGestureCallBack(this);

//		lockBar.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				LockRegulate();
//			}
//		});
	}
	
	/**
	 * 获取保存的亮度值,默认30%亮度显示
	 */
	private float getBrightnessFromSharedPreferences() {
		SharedPreferences p = activity.getSharedPreferences("player_parameter",Context.MODE_PRIVATE);
		return p.getFloat("britness", 0.3f);
	}
	
	/**
	 * 存储亮度
	 */
	private void saveBrightnessToSharedPreferences(float brightness) {
		SharedPreferences p = activity.getSharedPreferences("player_parameter",Context.MODE_PRIVATE);
		Editor editor= p.edit();
		editor.putFloat("britness", brightness);
		editor.commit();
	}
	

	/**
	 * 得到最大亮度
	 * */
	public int getMaxBrightness() {
		return 255;
	}

	/**
	 * 得到当前亮度
	 * */
	public int getCurBrightness() {
		WindowManager.LayoutParams wl = activity.getWindow().getAttributes();
		float br = wl.screenBrightness;
		if (br < 0) {
			br = 0.1f;
			 setBrightness(br);
		}
		return (int) (br * 255);
	}

	/**
	 * 初始化手势声音布局
	 * */
	public void initVolume(int cur, int max) {
		int curPercent = (int)((float)cur / max * 100);
		if (volumeTextView != null) {
			volumeTextView.setText(curPercent + "%");
		}
		setVolumeIcon(curPercent);
	}
	
	private void setVolumeIcon(int curPercent){
		if(curPercent == 0){
			volumeIcon.setImageResource(R.drawable.letv_local_sound_zero);
		} else if(curPercent > 0 && curPercent <= 30){
			volumeIcon.setImageResource(R.drawable.letv_local_sound_one);
		} else if(curPercent > 30 && curPercent <= 60){
			volumeIcon.setImageResource(R.drawable.letv_local_sound_two);
		} else {
			volumeIcon.setImageResource(R.drawable.letv_local_sound_three);
		}
	}

	/**
	 * 初始化手势亮度布局
	 * */
	public void initBrightness(int cur, int max) {
		if (brightnessTextView != null) {
			int curPercent = (int)((float)cur / max * 100);
			brightnessTextView.setText(curPercent + "%");
		}
	}
	
	/**
	 * 得到当前音量
	 * */
	public int getCurSoundVolume() {
		return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	}
	
	/**
	 * 得到最大音量
	 * */
	public int getMaxSoundVolume() {
		return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	}
	
	/**
	 * 调节音量
	 * */
	public int setSoundVolume(int value, boolean isShow) {
		int maxValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		if (value >= 0 && value <= maxValue) {
			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value, 0);
			volumeRegulate(isShow, value, maxValue);
		}

		return maxValue;
	}
	
//	/**
//	 * 调节音量
//	 * */
//	public void onSoundChange(int value) {
//		int maxValue = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
////		Log.i("chenyg", "setSoundVolume(), value=" + value);
//		if (value >= 0 && value <= maxValue) {
//			audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value, 0);
//			volumeRegulate(false, value);
//		}
//	}

	/**
	 * 设置亮度
	 * */
	public void setBrightness(float value) {
		if (value > 1) {
			value = 1;
		}
		if (value < 0.1f) {// 亮度不能为 0 要不会黑屏
			value = 0.1f;
		}
		WindowManager.LayoutParams wl = activity.getWindow().getAttributes();
		wl.screenBrightness = value;
		activity.getWindow().setAttributes(wl);
		
		saveBrightnessToSharedPreferences(value);
	}

	/**
	 * 调节亮度
	 * */
	public void brightnessRegulate(boolean isShow, int pos, int max) {
		if (isShow) {
			if (brightnessLayout.getVisibility() != View.VISIBLE) {
				brightnessLayout.setVisibility(View.VISIBLE);
			}
		}
		
		initBrightness(pos, max);
	}

	/**
	 * 调节声音
	 * */
	public void volumeRegulate(boolean isShow, int pos, int max) {
		if (isShow) {
			if (volumeLayout.getVisibility() != View.VISIBLE) {
				volumeLayout.setVisibility(View.VISIBLE);
			}
		}

		initVolume(pos, max);
	}

	/**
	 * 调节进度
	 * */
	public void progressRegulate(int curPos, int total) {
		if (progressLayout != null && progressLayout.getVisibility() != View.VISIBLE) {
			progressLayout.setVisibility(View.VISIBLE);
		}

		if (progressTextView != null) {
			progressTextView.setText(Tools.stringForTime(curPos));
		}

		if (totalTextView != null) {
			totalTextView.setText(Tools.stringForTime(total));
		}
		
		boolean forward = oldP <= curPos ? true : false;
		if(forward){
			progressIcon.setImageResource(R.drawable.letv_local_forword);
		} else {
			progressIcon.setImageResource(R.drawable.letv_local_rewind);
		}
		oldP = curPos;
		
		gestureProgress.setProgress(curPos);
		gestureProgress.setMax(total);
	}

    /**
     * 设置进度调可见性
     * @param toVisible
     */
    public void setProgressVisible(boolean toVisible){
        if (progressLayout != null) {
            progressLayout.setVisibility(toVisible ? View.VISIBLE : View.GONE);
        }
    }
	/**
	 * lock状态
	 * */
	public void LockRegulate() {
//		isLock = !isLock;
//		lockBar.setImageResource(isLock ? R.drawable.lock : R.drawable.unlock);
//		if (isLock) {
//			MessageBean dialogMsgByMsg = DBManager.getInstance().getDialogMsgTrace().getDialogMsgByMsgId(DialogMsgConstantId.CONSTANT_20005);
//			if (dialogMsgByMsg == null) {
//				UIs.showToast(getActivity().getResources().getString(R.string.play_operation_lock));
//			} else {
//				UIs.showToast(dialogMsgByMsg.message);
//			}
//
//		} else {
//			MessageBean dialogMsgByMsg = DBManager.getInstance().getDialogMsgTrace().getDialogMsgByMsgId(DialogMsgConstantId.CONSTANT_20006);
//			if (dialogMsgByMsg == null) {
//				UIs.showToast(getActivity().getResources().getString(R.string.play_operation_unlock));
//			} else {
//				UIs.showToast(dialogMsgByMsg.message);
//			}
//
//		}
//		activity.getmOrientationSensorListener().setLock(isLock);
	}

	public int getBrightness() {
		WindowManager.LayoutParams wl = activity.getWindow().getAttributes();
		float br = wl.screenBrightness;
		if (br < 0) {
			br = 0.1f;
		}
		return (int) (br * 255);
	}

//	public boolean isLock() {
//		return isLock;
//	}

	public void onDestroy() {
		activity = null;
		brightnessLayout = null;
		volumeLayout = null;
		brightnessTextView = null;
		volumeTextView = null;
		lockBar = null;
		progressLayout = null;
		progressTextView = null;
		totalTextView = null;
	}

	protected abstract void readArguments();
	protected abstract void initLayout();
	public abstract void changeVolumeByTouch(int progrees, int max);
	public abstract void changeProgressByTouch(int curPos, int total, boolean isfinish);

	//-------------------------------------------------------------------
	@Override
	public void onDown() {
		oldV = getCurSoundVolume();
		oldB = getBrightness();
		oldP = activity.getPlayFragment().getCurrentPosition();
	}

	@Override
	public void onDoubleFingersDown() {
		
	}

	@Override
	public void onDoubleFingersUp() {
		
	}

	@Override
	public void onDoubleTap() {
		
	}

	@Override
	public void onRightScroll(float incremental) {
		int max = getMaxSoundVolume();
		int newVlaue = oldV + (int) (max * incremental);
		if (newVlaue < 0) {
			newVlaue = 0;
		}
		if (newVlaue > max) {
			newVlaue = max;
		}
		setSoundVolume(newVlaue, true);
		changeVolumeByTouch(newVlaue, max);
	}

	int currentB = 0;
	
	@Override
	public void onLeftScroll(float incremental) {
        int max = getMaxBrightness();
		if(currentB == 0){
			oldB = getMaxBrightness()*30/100;
            float bright= getBrightnessFromSharedPreferences();
            oldB = (bright== 0? oldB: (int)(bright* max));
			currentB = oldB;
		}
		int newVlaue = oldB+ (int)Math.floor((int) (max * incremental));
		if (newVlaue < 0) {
			newVlaue = 0;
		}
		if (newVlaue > max) {
			newVlaue = max;
		}

		brightnessRegulate(true, newVlaue, max);
		setBrightness((float) newVlaue / max);
	}

    @Override
    public void onSingleTapUp() {
        if (mBasePlayerPannel != null) {
        	mBasePlayerPannel.showOrHidePannel();
        }
    }

    @Override
    public void onLandscapeScroll(float incremental) {
        if (activity.getPlayFragment().isInPlaybackState()) {
	    	
            int duration = activity.getPlayFragment().getDuration();
            int cur = activity.getPlayFragment().getCurrentPosition();
            
            /**
			 * 当片源长度大于3min时，从屏幕左端滑动到右端进度条前进3min，否则等于整个视频的长度
			 */
			int total = duration > 3 * 60 * 1000 ? 3 * 60 * 1000 : duration;
            
            int newcur = cur + (int) (incremental * total);
            if (newcur < 0) {
                newcur = 1;
            }

            if (newcur > duration) {
                newcur = duration;
            }
            Log.i("chenyg", "onLandscapeScroll(), incremental=" + incremental + ", newcur=" + newcur + ", duration=" + duration);
            progressRegulate(newcur, duration);
            changeProgressByTouch(newcur, duration, false);
            
        }
    }

    @Override
    public void onLandscapeScrollFinish(float incremental) {
    	if (activity.getPlayFragment().isInPlaybackState()) {
    		
	        int duration = activity.getPlayFragment().getDuration();
	        int cur = activity.getPlayFragment().getCurrentPosition();
	        /**
			 * 当片源长度大于3min时，从屏幕左端滑动到右端进度条前进3min，否则等于整个视频的长度
			 */
			int total = duration > 3 * 60 * 1000 ? 3 * 60 * 1000 : duration;
	        
	        int pos = cur + (int) (incremental * total);
	        if (pos < 0) {
	            pos = 1;
	        }
	        if (pos > duration) {
	            pos = duration;
	        }
	        Log.i("chenyg", "onLandscapeScrollFinish(), incremental=" + incremental + ", pos=" + pos + ", duration=" + duration);
	        progressRegulate(pos, duration);
	        changeProgressByTouch(pos, duration, true);
	        
	        activity.getPlayFragment().seekTo(pos);
    	}
    }

	@Override
	public void onTouchEventUp() {
		volumeLayout.setVisibility(View.GONE);
		brightnessLayout.setVisibility(View.GONE);
		progressLayout.setVisibility(View.GONE);
	}

	@Override
	public void onLongPress() {
		
	}
	
}
